import 'dart:math';

import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter_member/stytle/listview_overScrollbehavior.dart';
import 'package:flutter_member/utils/math_distance.dart';
import 'package:flutter_member/widget/distance_widget.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:loading_animations/loading_animations.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:toast/toast.dart';

class CampusNetworkDetailsPage extends StatefulWidget {
  final objectId;

  const CampusNetworkDetailsPage({Key key, this.objectId}) : super(key: key);

  @override
  _CampusNetworkDetailsPageState createState() =>
      _CampusNetworkDetailsPageState();
}

class _CampusNetworkDetailsPageState extends State<CampusNetworkDetailsPage> {
  TabController _tabController;

  /// 分校详情
  var branch = ParseObject("Branch");

  /// 学校相册
  List<dynamic> listAlbums = [];

  //開辦課程
  List<OfferingCourses> _offeringCoursesList = [
    OfferingCourses(
        "id", null, "課程名稱", DateTime.now(), DateTime.now(), "address", 1)
  ];

  // 加载中
  bool _loading = true;
  /// 图片集
  List<String> imgs = [
    'images/1.jpg',
    'images/2.jpg',
    'images/3.jpg',
    'images/3.jpg'
  ];

  get _objectId => widget.objectId;

  /// 位置
  Location _location;
  @override
  void initState() {
    super.initState();
    print(_objectId[0]);
    getBranch();
    _getLocation();
  }
  //本地
  ParseGeoPoint point = new ParseGeoPoint();
  /// 获取分店详情
  Future<void> getBranch() async {
    var query = QueryBuilder<ParseObject>(ParseObject("Branch"))
      ..whereEqualTo("objectId", _objectId[0])
      ..includeObject(["contacts", "businessHours"]);
    var rep = await query.query();

    var queryAlbum = QueryBuilder<ParseObject>(ParseObject("Album"))
      ..whereRelatedTo("albums", "Branch", _objectId[0]);
    var repAlbum = await queryAlbum.query();
    if (repAlbum.results != null && repAlbum.success) {
      print("+++${repAlbum.results}");
    }
    if (rep.results != null && rep.success) {
      setState(() {
        _loading=false;
        point = rep.results.first["location"];
        branch = rep.results.first;
      });
      print(branch);
    } else {
      setState(()=>_loading=false);
      print("空的");
    }
  }
  /// 获得当前经纬度
  Future<void> _getLocation() async {
    if (await requestPermission()) {
      final location = await AmapLocation.instance.fetchLocation();
      setState(() => _location = location);
    }
  }

  Future<bool> requestPermission() async {
    final permissions = await Permission.locationWhenInUse.request();

    if (permissions.isGranted) {
      return true;
    } else {
      Toast.show("需要定位权限", context);
      return false;
    }
  }
  /*-------------高德地圖定位end ----------------*/
  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    return Scaffold(
      body: ScrollConfiguration(
        behavior: OverScrollBehavior(),
        child: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverAppBar(
                expandedHeight: ScreenUtil().setHeight(181),
                floating: true,
                snap: false,
                pinned: true,
                backgroundColor: Color(0xff154D7C),
                leading: IconButton(
                  icon: Icon(
                    Icons.arrow_back,
                    color: Colors.white,
                    size: ScreenUtil().setSp(24),
                  ),
                  onPressed: () => Navigator.pop(context),
                ),
                flexibleSpace: FlexibleSpaceBar(
                  centerTitle: true,
                  background: Container(
                    child: new Swiper(
                      itemBuilder: (BuildContext context, int index) {
                        return new Image.asset(
                          imgs[index],
                          fit: BoxFit.cover,
                        );
                      },
                      itemCount: imgs.length,
                      pagination: new SwiperPagination(), //如果不填则不显示指示点
                    ),
                  ),
                ),
              ),
            ];
          },
          body: _loading==true?CLoadingDialog(text: "加载中",):contentWidget(width, height),
        ),
      ),
    );
  }

  Widget contentWidget(width, height) {
    return Container(
//      padding: EdgeInsets.only(top: 268),
      child: Stack(
        children: <Widget>[
          Container(
            width: width,
            height: height,
            decoration: BoxDecoration(
                color: Color(0xffc8daee),
                borderRadius: BorderRadius.all(Radius.circular(20))),
          ),
          Container(
              margin: EdgeInsets.fromLTRB(0.0, 6, 0.0, 0.0),
              height: height,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(20))),
              child: Container(
                child: DefaultTabController(
                    length: 2,
                    child: Column(
                      children: <Widget>[
                        TabBar(
                          //指示器高度
                          indicatorWeight: 3,
                          //指示器大小
                          indicatorSize: TabBarIndicatorSize.label,
                          //指示器顏色
                          indicatorColor: Color(0xffFFC82C),
                          indicatorPadding: EdgeInsets.fromLTRB(0, 0, 40, 0),
                          //選中樣式
                          unselectedLabelColor: Color(0Xff7B7B7B),
                          unselectedLabelStyle: TextStyle(
                              color: Color(0Xff7B7B7B),
                              fontSize: ScreenUtil().setSp(16)),
                          //未選中樣式
                          labelColor: Color(0Xff2D7FC7),
                          labelStyle: TextStyle(
                              color: Color(0Xff2D7FC7),
                              fontSize: ScreenUtil().setSp(16)),

                          tabs: <Widget>[
                            Tab(
                              text: '分校詳情',
                            ),
                            Tab(
                              text: '開辦課程',
                            ),
                          ],
                          controller: _tabController,
                        ),
                        Expanded(
                          child: TabBarView(
                            children: <Widget>[
                              //分校詳情
                              ListView(
                                padding: EdgeInsets.only(
                                    left: 30, top: 10, right: 30),
                                children: <Widget>[
                                  Container(
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: <Widget>[
                                        new Expanded(
                                          child: Text(
                                            branch != null
                                                ? branch.get("displayName")
                                                : "空",
                                            style: TextStyle(
                                                color: Color(0xff2D7FC7),
                                                fontSize:
                                                    ScreenUtil().setSp(18),
                                                fontWeight: FontWeight.w600),
                                          ),
                                          flex: 3,
                                        ),

                                        DistanceWidget(distance:_location==null?0: MathDistance.getDistance(_location.latLng.longitude,
                                            _location.latLng.latitude, point.longitude, point.latitude),),
                                      ],
                                    ),
                                    padding: EdgeInsets.only(bottom: 10),
                                  ),
                                  _titleWidget(
                                      iconSrc:
                                          "images/icons_event_location.png",
                                      title: branch.get("address")),
                                  _titleWidget(
                                      iconSrc: "images/icons_info_phone.png",
                                      title: "28921492/6569635"),
                                  _titleWidget(
                                      iconSrc: "images/icons_info_mail.png",
                                      title: 'ljx@qq.com'),
                                  Container(
                                    padding: EdgeInsets.only(top: 15),
                                    child: Column(
                                      children: <Widget>[
                                        curriculumDetailsTitle(
                                          width,
                                          '簡介',
                                          ScreenUtil().setSp(18),
                                        ),
                                        Container(
                                          child: curriculumDetailsContent(
                                              width,
                                              "這裡我們儒林教育集團於2013年成立的第一家店(專補聖羅撒、培道和教業學校)。我們秉著對教育滿滿的熱忱，一直以學生為中心，致力提供優質的教育及促進幼童身心發展為目標，立志為澳門教育做貢獻。非常感謝家長一直以來對我們的支持和鼓勵，讓我們有了對教育事業的使命感并堅定我們在教育路上走得更加長遠的決定！我們一路見證著學生們的成長，看到你們每一次的進步，每一次的獲獎，每一次向我們展露開心的笑臉，你們那一份份喜悅的笑臉一直刻在我們心裡。",
                                              ScreenUtil().setSp(13),
                                              Color(0xff9C9C9C)),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      Container(
                                        width: ScreenUtil().setWidth(200),
                                        child: gradientButton(),
                                      )
                                    ],
                                  )
                                ],
                              ),
                              //開辦課程
                              ScrollConfiguration(
                                behavior: OverScrollBehavior(),
                                child: ListView.separated(
                                    itemBuilder:
                                        (BuildContext context, int index) =>
                                            _buildRowOfferingCourses(index),
                                    separatorBuilder:
                                        (BuildContext context, int index) =>
                                            Container(
                                              height: 10,
                                            ),
                                    itemCount: _offeringCoursesList.length),
                              ),
                            ],
                          ),
                        )
                      ],
                    )),
              )),
        ],
      ),
    );
  }

  /// 带icon的文本

  Widget _titleWidget(
      {@required String iconSrc,
      @required String title,
      num titleColor = 0xff154D7C,
      VoidCallback onTop}) {
    return GestureDetector(
      onTap: onTop,
      child: Container(
        padding: EdgeInsets.only(
          top: 15,
        ),
        child: Row(
          children: <Widget>[
            ImageIcon(
              AssetImage(iconSrc),
              color: Color(0xffFFC82C),
              size: ScreenUtil().setSp(16),
            ),
            Container(
              width: 10,
            ),
            new Expanded(
              child: Text(
                title != null ? title : "空",
                style: TextStyle(
                  color: Color(titleColor),
                  fontSize: ScreenUtil().setSp(13),
                  fontWeight: FontWeight.bold,
                  fontFamily: "SemiBold",
                ),
              ),
              flex: 8,
            )
          ],
        ),
      ),
    );
  }

  Widget titleWidget(ImageIcon icon, String title, Color titleColor) {
    return Container(
      padding: EdgeInsets.only(
        top: 15,
      ),
      child: Row(
        children: <Widget>[
          icon,
          Container(
            width: 10,
          ),
          new Expanded(
            child: Text(
              title,
              style: TextStyle(
                color: titleColor,
                fontSize: ScreenUtil().setSp(13),
                fontWeight: FontWeight.bold,
                fontFamily: "SemiBold",
              ),
            ),
            flex: 8,
          )
        ],
      ),
    );
  }

  Widget gradientButton() {
    return Container(
      width: ScreenUtil().setWidth(200),
      height: ScreenUtil().setWidth(50),
      margin: EdgeInsets.only(top: 20, bottom: 20),
      decoration: BoxDecoration(
          gradient: LinearGradient(
              colors: [Color(0xff82b518), Color(0xff3e73b7)]), // 渐变色
          borderRadius: BorderRadius.circular(50)),
      child: RaisedButton(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
        color: Colors.transparent,
        // 设为透明色
        elevation: 0,
        // 正常时阴影隐藏
        highlightElevation: 0,
        // 点击时阴影隐藏
        onPressed: () {},
        child: Container(
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ImageIcon(
                  AssetImage('images/group.png'),
                  color: Color(0xffFFFFFF),
                  size: ScreenUtil().setSp(23),
                ),
                SizedBox(width: 10),
                Text(
                  '報名補習',
                  style: TextStyle(
                      color: Color(0xffFFFFFF),
                      fontSize: ScreenUtil().setSp(16)),
                ),
              ],
            ) //
            ),
      ),
    );
  }

  //開辦課程子組件
  Widget _buildRowOfferingCourses(int index) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(context, '/curriculumDetails',
            arguments: {'objectId': _offeringCoursesList[index].objectId});
      },
      child: Card(
        margin: EdgeInsets.only(left: 10, right: 10),
        elevation: 5,
        //设置shape，这里设置成了R角
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
        ),
        child: Container(
          height: ScreenUtil().setHeight(169),
          padding: EdgeInsets.all(10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                height: ScreenUtil().setHeight(147),
                width: ScreenUtil().setWidth(128),
                decoration: BoxDecoration(
                  image: DecorationImage(
                      image: _offeringCoursesList[index].src != null
                          ? NetworkImage(
                              _offeringCoursesList[index].src,
                            )
                          : AssetImage('images/noimg.jpg'),
                      fit: BoxFit.cover),
                  borderRadius: BorderRadius.circular(15),
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 10),
                height: ScreenUtil().setHeight(140),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    //分校名稱
                    Container(
                      child: myContainer(
                          MediaQuery.of(context).size.width,
                          _offeringCoursesList[index] != null
                              ? _offeringCoursesList[index].title
                              : '暫無數據',
                          22,
                          Color(0xff154d7c),
                          0),
                    ),
                    //日期
                    Container(
                      child: Row(
                        children: <Widget>[
                          Icon(Icons.event_note,
                              color: Color(0xff9ea3ba), size: 18),
                          myContainer(
                              MediaQuery.of(context).size.width,
                              _offeringCoursesList[index] != null
                                  ? '${_offeringCoursesList[index].startDate.month}月${_offeringCoursesList[index].startDate.day}日' +
                                      '-${_offeringCoursesList[index].endDate.month}月${_offeringCoursesList[index].endDate.day}日（逢星期六 17：30 - 19：30）'
                                  : '暫無數據',
                              14,
                              Color(0xffb9bdc5),
                              18),
                        ],
                      ),
                    ),
                    //地址
                    Container(
                      child: Row(
                        children: <Widget>[
                          Icon(Icons.location_on,
                              color: Color(0xffb9bdc5), size: 18),
                          myContainer(
                              MediaQuery.of(context).size.width,
                              _offeringCoursesList[index] != null
                                  ? _offeringCoursesList[index].address
                                  : '暫無數據',
                              14,
                              Color(0xffb9bdc5),
                              18),
                        ],
                      ),
                    ),
                    //剩餘名額
                    Container(
                      child: Row(
                        children: <Widget>[
                          myContainer(
                              MediaQuery.of(context).size.width,
                              _offeringCoursesList[index] != null
                                  ? '剩餘名額：${_offeringCoursesList[index].surplusQuota}位'
                                  : '暫無數據',
                              14,
                              Colors.red,
                              18),
                        ],
                      ),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(170),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Container(
                              width: ScreenUtil().setWidth(89),
                              height: ScreenUtil().setHeight(20),
                              decoration: BoxDecoration(
                                border: new Border.all(
                                    width: 2, color: Color(0xffc9dd91)),
                                borderRadius: BorderRadius.circular(30),
                              ),
                              child: Center(
                                child: Text(
                                  '距離<125m',
                                  style: TextStyle(
                                    color: Color(0xff93BB24),
                                    fontSize:
                                        ScreenUtil().setSp(12),
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ))
                        ],
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
  //課程詳情內容文本
  Widget curriculumDetailsContent(double width,String text,double fontSize,Color color){
    return Container(
      margin: EdgeInsets.only(top: 5),
      width: width-110,
      child: Text(
        text,
        style: TextStyle(
          fontSize: fontSize,
          fontWeight: FontWeight.bold,
          color: color,
          fontFamily:"SemiBold",
        ),
        softWrap: true,
      ),
    );
  }
  //分校信息文本框
  Widget myContainer(double width, String param, double textSize, Color color,double iconSize) {
    return Container(
      width: ScreenUtil().setWidth(160),
      child: Text(
        param,
        //最大行數
        maxLines: 2,
        //overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontWeight: FontWeight.bold, fontSize: textSize, color: color,fontFamily:"SemiBold",),
      ),
    );
  }
  //課程詳情標題文本
  Widget curriculumDetailsTitle(double width,String title,double fontsize){
    return Container(
      width: width,
      child: Text(
        title,
        style: TextStyle(
            fontSize: fontsize,
            fontWeight: FontWeight.bold,
            color: Color(0xff93BB24)
        ),
      ),
    );
  }
}


class OfferingCourses {
  final String objectId;
  final String src;
  final String title;
  final DateTime startDate;
  final DateTime endDate;
  final String address;
  final int surplusQuota;

  OfferingCourses(this.objectId, this.src, this.title, this.startDate,
      this.endDate, this.address, this.surplusQuota);
}
